package com.vn.rainbow.exoalarm.db.table;

import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.vn.rainbow.exoalarm.db.element.AlarmElement;
import com.vn.rainbow.exoalarm.db.element.BaseElement;
import com.vn.rainbow.exoalarm.db.element.DetailAlarmElement;
import com.vn.rainbow.exoalarm.db.settings.AlarmSettingColums;
import com.vn.rainbow.exoalarm.db.settings.DetailSettingColums;

public class DetailSettingTable {
	public static final String TABLE_NAME = "DetailAlarmSeting";

	public static void onCreate(SQLiteDatabase database) {
		final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
				+ DetailSettingColums._ID + " INTEGER PRIMARY KEY,"
				+ DetailSettingColums.ID_ALARM + " INTEGER,"
				+ DetailSettingColums.TIME_ALARM + " INTEGER,"
				+ DetailSettingColums.ACTIVE_ALARM + " INTEGER" + ");";
		database.execSQL(CREATE_TABLE);
	}

	public static void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
	}

	public synchronized static void getAllDetail(Context context,
			List<BaseElement> mResult) {
		final ContentResolver cr = context.getContentResolver();
		Cursor cursor = cr.query(DetailSettingColums.CONTENT_URI, null, null,
				null, null);
		try {
			DetailAlarmElement.parse(cursor, mResult);
			cursor.close();
		} catch (Exception e) {
			cursor.close();
		}
	}

	public static boolean isDetailAlarmExist(Context context, String _id) {
		final ContentResolver cr = context.getContentResolver();
		final String[] projection = { DetailSettingColums._ID };
		Cursor cursor = cr.query(DetailSettingColums.CONTENT_URI, projection,
				DetailSettingColums._ID + "=" + _id, null, null);
		if (cursor != null) {
			if (cursor.getCount() > 0) {
				cursor.close();
				return true;
			} else {
				cursor.close();
			}
		}
		return false;
	}

	public synchronized static DetailAlarmElement getAlarmInfoFromId(
			Context context, String id) {
		DetailAlarmElement info = null;
		final ContentResolver cr = context.getContentResolver();
		final String[] projection = { DetailSettingColums._ID,
				DetailSettingColums.ID_ALARM, DetailSettingColums.TIME_ALARM,
				DetailSettingColums.ACTIVE_ALARM };
		Cursor cursor = cr.query(DetailSettingColums.CONTENT_URI, projection,
				DetailSettingColums._ID + "=" + id, null, null);
		try {
			cursor.moveToFirst();
			info = DetailAlarmElement.parse(cursor);
			cursor.close();
			return info;
		} catch (Exception e) {
			// TODO: handle exception
			cursor.close();
		}
		return info;
	}
}
